package cn.seaboot.flake.jdbc;

import cn.seaboot.commons.reflect.FieldAccess;
import cn.seaboot.commons.reflect.ObjectField;
import org.jetbrains.annotations.NotNull;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * 将查询到的数据打包成对象
 *
 * @author Mr.css
 * @version 2020-11-15 10:41
 */
public class ObjectResultSetExtractor<T> implements ResultSetExtractor<List<T>> {

    /**
     * 需要转换的 VO 类型
     */
    private final Class<T> clazz;
    /**
     * 字段映射
     * <p>
     * 数组下标需要与结果集下标保持一致，下标从 0 开始
     */
    private final Map<String, String> mapping;

    /**
     * -
     *
     * @param clazz   目标类型
     * @param mapping 结果集字段序号对应的字段名列表
     */
    public ObjectResultSetExtractor(Class<T> clazz, Map<String, String> mapping) {
        this.clazz = clazz;
        this.mapping = mapping;
    }

    @Override
    public List<T> extractData(@NotNull ResultSet rs) throws SQLException, DataAccessException {
        FieldAccess access = FieldAccess.create(clazz);
        return JdbcUtils.toObject(rs, access, mapping);
    }
}
